package com.hdax.dm.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.hdax.dm.common.utils.CommonResponse;
import com.hdax.dm.common.utils.ResponseUtil;
import com.hdax.dm.constants.ResultEnumCode;
import com.hdax.dm.dtos.user.UserDto;
import com.hdax.dm.exceptions.DmException;
import com.hdax.dm.service.UserLoginService;
import com.hdax.dm.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping(path = "/user")
public class MsgLoginController {

    @Autowired
    private UserLoginService userLoginService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @PostMapping(path = "msg")
    public CommonResponse msg(@RequestBody Map<String,String> params) throws Exception {
        String phoneNumber = params.get("phone");
        //生成验证码并存储到redis缓存中
        String vcode = userLoginService.generateVCode(phoneNumber);
        return ResponseUtil.returnSuccess("验证码发送成功");
    }

    //短信验证码登录系统
    @PostMapping(path = "msg/login")
    public CommonResponse login(@RequestBody Map<String,String> params){

        String phoneNumber = params.get("phone");
        String vcode = params.get("vcode");
        CommonResponse<UserDto> dtoResponse = userLoginService.msgLogin(phoneNumber, vcode);
        //生成token
        String token = TokenUtil.createToken(BeanUtil.beanToMap(dtoResponse.getData(),new HashMap<>(),false,true));
        //添加token信息到Redis缓存中
        //缓存数据的过期时间为token有效期的2倍
        Map<String, String> redisData = new HashMap<>();
        redisData.put("userId",dtoResponse.getData().getUserId().toString());
        redisData.put("phone",dtoResponse.getData().getPhone());
//        redisData.put("nickName",dtoResponse.getData().getNickName());
        redisData.put("realName",dtoResponse.getData().getRealName());
        redisData.put("token",token);
        redisTemplate.opsForHash().putAll("token:"+dtoResponse.getData().getUserId(),redisData);
        redisTemplate.expire("token:"+dtoResponse.getData().getUserId(),TokenUtil.TOKEN_EXPIRE_TIME * 2, TimeUnit.MILLISECONDS);
        dtoResponse.getData().setToken(token);
        return dtoResponse;
    }


}
